import dayjs from 'dayjs'
// 计算年龄
export function calculateAge(timestamp) {
  if (!timestamp || timestamp == 0) return '-'

  const birthDate = new Date(timestamp)
  const today = new Date()

  let age = today.getFullYear() - birthDate.getFullYear()
  const monthDiff = today.getMonth() - birthDate.getMonth()

  if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
    return '--'
  }

  return age
}

export function formatDate(date, format) {
  // 日期不存在，则返回空
  if (!date) {
    return ''
  }
  // 日期存在，则进行格式化
  return date ? dayjs(date).format(format ?? 'YYYY-MM-DD HH:mm:ss') : ''
}

export function openIframeWindow(
  url,
  windowName = "iframeWindow",
  width = 800,
  height = 600
) {
  // 计算窗口位置居中
  const left = (window.screen.width - width) / 2;
  const top = (window.screen.height - height) / 2;
  return window.open(url)
  // 打开新窗口
  const newWin = window.open(
    "",
    windowName,
    `
    width=${width},
    height=${height},
    left=${left},
    top=${top},
    toolbar=no,
    location=no,
    directories=no,
    status=no,
    menubar=no,
    scrollbars=yes,
    resizable=yes
  `
  );

  if (newWin) {
    // 创建iframe并添加到新窗口
    const iframe = newWin.document.createElement("iframe");
    iframe.src = url;
    iframe.style.width = "100%";
    iframe.style.height = "100%";
    iframe.style.border = "none";

    newWin.document.body.style.margin = "0";
    newWin.document.body.style.padding = "0";
    newWin.document.body.style.overflow = "hidden";
    newWin.document.body.appendChild(iframe);
  } else {
    console.warn("弹出窗口被阻止");
  }
}